/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step_fliter',
			title : 'Step过滤',
			type : 'LineEdit',
			property : {tool_tip : 'unit'},
		},
		{
            name : 'checklist_cfg',
			title : 'checklist配置',
			type : 'TextEdit',
            property : {tool_tip : 'checklist配置'},
            setter:function(obj,value,self){
                obj.setPlainText(value);
            },
            getter:function(obj,self){
                return obj.plainText
            }
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-05-13 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 钻孔分析 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>JTG_DRILL_analysis_aim start");
/* question
    ?
*/
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {  // par默认参数？
		step_fliter:"unit.+",
		step2:"unit",
		units: "mm",
		auto_save: "no"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(par.checklist_cfg == ""){
		throw "无checklist配置"
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
    // 脚本开始
    var matrix = GEN.getMatrix({job:job})
    var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
    .filter(function(key){
        var val = matrix[key]
        return val.layer_type == "drill" && val.context == "board"
    })
    if(n_layers.length == 0){throw "can not find layer"}
	var stepList = GEN.getStepList({job:job})
	if(par.step_fliter != ""){
		stepList = stepList.filter(function(v){
			var step_reg = new RegExp(par.step_fliter) 
			return step_reg.test(v)})
	}
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	var chk = JSON.parse(par.checklist_cfg)
	var chkname = Object.keys(chk)[0]
	var info = {
        drill_spacing_min: ["closeh"]
	}
	var layer_attr = {}
	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.units({type:par.units})
		GEN.clearLayers()
		GEN.affectedLayer({affected:"yes", layer:n_layers, clear_before:"yes"})
		// 检查chklist是否存在 不存在时去lib看
		if(!GEN.isChklistExists({job:job,step:step,chklist:chkname})){
			if(GEN.getChecklist({job:"genesislib",step:"checklib"}).indexOf(chkname) >= 0){
				GEN.chklistFromLib({chklist:chkname})
			} else {
				throw "lib can not find chk:"+ chkname
			}
		}
		GEN.chklistShow({ chklist: chkname })
		chk[chkname].forEach(function(nact){
			GEN.chklistRun({
				chklist: chkname,
				nact: nact,
				area: 'profile',
			})
			GEN.COM("chklist_res_show,chklist="+chkname+",nact=1,x=0,y=0,w=0,h=0")
		})
		// n_layers.forEach(function(layer){
		// 	if(!layer_attr[layer]){layer_attr[layer] = {}}
		// 	var syms = GEN.getLayerSymsHist({job:job,step:step,layer:layer,units:'inch'})
		// 	layer_attr[layer].drill_size_min = _.values(syms).reduce(function(a,b){
		// 		if(!b.size){b.size = b.width>b.height? b.width :b.height}
		// 		if(a == "head") { a = b.size}
		// 		if(a > b.size) {
		// 			a = b.size
		// 		}
		// 		return Number(a) 
		// 	}, "head")
		// })
        // analysisChkAttr({layers:n_layers, info:info, step:step, job:job, oChecklistName:chkname, layer_attr:layer_attr})
		
		GEN.affectedLayer({affected:"no", mode:"all"})
	})
	var job_info_keys = ["drill_size_min", "drill_spacing_min"]
	var job_attr = {}
	// layer_attr : {"drl":{"drill_size_min":12,"drill_spacing_min":"1.0953"}}
	Object.keys(layer_attr).forEach(function(key){
		var val = layer_attr[key]
		for(var key2 in val){
            if(job_info_keys.indexOf(key2)>=0){
			var val2 = val[key2]
                if(val2 != "" && val2 != "N/A"){
                        if(!job_attr[key2] || job_attr[key2]=="N/A"){job_attr[key2] = val2}
                        if(job_attr[key2] > val2){job_attr[key2] = val2}
                    
                } else if(val2 == "N/A"){
                    if(!job_attr[key2]){job_attr[key2] = val2}
                }
            }
		}
		IKM.save_layerinfo({
			jobid: JobId,
			layer: key,
			layerinfohash: val
		})
	})
	console.log(_.toString(job_attr))
	IKM.save_job_info({
        jobid: JobId,
        jobinfohash: job_attr
    })
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
    console.log("========================JTG_DRILL_analysis_aim end");
    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function analysisChkAttr(par) {
    var layers = par.layers;
	var layer_attr = par.layer_attr
    var info = par.info;
    var job = par.job;
    var oChecklistName = par.oChecklistName
    layers.forEach(function (v) {
		if(!layer_attr[v]){layer_attr[v] = {}}
        Object.keys(info).forEach(function (key) {
            var val = info[key]
            layer_attr[v][key] = val.reduce(function (a, type) {
                var tmp = GEN.getCheckAttr({
                    job: job,
                    step: par.step,
					checklist: oChecklistName,
                    nact: 1,
					attr: v + "_min_" + type,
					units:"mm"
				})
				tmp = tmp / 25.4
                if (a === "N/A" && /\d+/.test(tmp)) {
                    tmp = Number(tmp)
                    a = tmp.toFixed(4)
                }
                if (/\d+/.test(a) && /\d+/.test(tmp) && Number(tmp) < Number(a)) {
                    tmp = Number(tmp)
                    a = tmp.toFixed(4)
                }
                return a
            }, "N/A")
        })
    })
}

function save_job_info(props){  //  保存料号信息
    var jobid = props.jobid;
    var jobinfohash = props.jobinfohash;
    Object.keys(jobinfohash).forEach(function(key){
        var val = jobinfohash[key];
        var value = db.query("",function(q){
            return q.selectValue({
                table:'pdm_job_jobattr',  
                field:"value", 
                where:{job_id:jobid, attr_name: key}
            })
        });
        console.log("jobid:"+jobid+"==========dbjobvalue:" + val)
        if(/done/ig.test(value) || !value){
            db.query("",function(q){
                return q.insertRow({
                    table:'pdm_job_jobattr',  // todo 
                    data:{job_id:jobid, attr_name:key, value:val}, // todo
                    return_field:'job_id',
                })
            });
        } else if (value != val) {
            console.log("jobid:"+jobid+"==========update jobvalue:"+value+"->" + val)
            db.query("",function(q){
                return q.updateRow({
                    table:'pdm_job_jobattr',
                    where:{job_id:jobid, attr_name: key},
                    data:{value:val},
                })
            });
        }
    })
}

function save_layerinfo(props){   //  保存层信息
    var jobid = props.jobid;
    var layer = props.layer;
    var layerinfohash = props.layerinfohash;
    Object.keys(layerinfohash).forEach(function(key){
        var val = layerinfohash[key];
        if(val && val != ""){
            var value = db.query("",function(q){
                return q.selectValue({
                    table:'pdm_job_layerattr',  
                    field:"value", 
                    where:{job_id:jobid, attr_name: key, layer:layer}
                })
            });
            console.log("+==========dblayervalue:" + value)
            if(/done/ig.test(value) || !value){
                db.query("",function(q){
                    console.log("+==========insertRowlayervalue:layer:"+layer+";attrname:"+key+";value:"+ val)
                    return q.insertRow({
                        table:'pdm_job_layerattr',  // todo 
                        data:{job_id:jobid, attr_name:key, value:val, layer:layer}, // todo
                        return_field:'job_id',
                    })
                });
            } else if (value !== val) {
                db.query("",function(q){
                    console.log("+==========updateRowlayer:layer:"+layer+";attrname:"+key+";value:"+ val)
                    return q.updateRow({
                        table:'pdm_job_layerattr',
                        where:{job_id:jobid, attr_name: key},
                        data:{value:val},
                    })
                });
            }
        }
    })
}